
"add the dom ready event (at bottom of page)"

from whiff.middleware import misc
from whiff import gateway

SCRIPTS_VARIABLE = "moo.DomReadyList"

TEMPLATE = """
<script>
window.addEvent('domready', function(){
  %s;
  });
</script>
"""
class addDomReadyEvent(misc.utility):
    def __init__(self, page, variable=SCRIPTS_VARIABLE):
        self.page = page
        self.variable = variable
    def __call__(self, env, start_response):
        env = env.copy()
        variable = self.param_value(self.variable, env)
        #scripts = env.get(variable, [])
        #env[variable] = scripts
        resource_path = ["local", variable]
        gateway.putResource(env, resource_path, [])
        pagetext = self.param_value(self.page, env)
        #scripts = env[variable]
        scripts = gateway.getResource(env, resource_path)
        all = ";\n".join(scripts)
        jspayload = TEMPLATE % all
        all = pagetext+jspayload
        return self.deliver_page(all, env, start_response)

__middleware__ = addDomReadyEvent
